package main

import (
	"flag"
	"fmt"
	"log"
	"net"
	"os"

	"probeping/src/funcs"
	"probeping/src/http"
	"probeping/src/model"
	"probeping/src/store"
	"probeping/src/utils"
	"runtime"

	"github.com/robfig/cron/v3"
)

var (
	Version = "1.0.2"
)

func main() {
	var err error
	runtime.GOMAXPROCS(runtime.NumCPU())
	utils.RotateFile()
	version := flag.Bool("v", false, "show version")
	flag.Parse()

	if *version {
		fmt.Println(Version)
		os.Exit(0)
	}

	utils.ParseConfig(Version)

	store.Host = model.Host{}
	store.Host.Name = store.Cfg.Name
	store.Host.Ip = store.Cfg.Addr
	interfaces, err := utils.GetAvailableInterfaces()
	if err != nil {
		log.Fatal(err)
	}
	store.Host.Interfaces = make([]model.Interface, len(interfaces))
	copy(store.Host.Interfaces[:], interfaces[:])
	for idx, intf := range store.Host.Interfaces {
		ipRange := utils.GetIpRange(intf.Ip)
		store.Host.Interfaces[idx].IpRange = make([]net.IP, len(ipRange))
		copy(store.Host.Interfaces[idx].IpRange[:], ipRange[:])
	}

	funcs.ClearArchive()

	c := cron.New()
	_, err = c.AddFunc("* * * * *", func() {
		go funcs.Ping()
	})
	if err != nil {
		log.Fatal(err)
	}
	c.AddFunc("0 * * * *", func() {
		go funcs.ClearArchive()
	})

	c.AddFunc("* * * * *", func() {
		go utils.RotateFile()
	})

	c.Start()
	http.StartHttp()

}
